package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.LowCodeHandlerFieldFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.abstracts.AbstractLowCodeHandlerFieldService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.pro.lowcodeexecute.pojo.LowCodeExecuteServicePojo;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/18 15:08
 */
@Service("lowCodeHandlerDepartmentService")
public class LowCodeHandlerDepartmentServiceImpl extends AbstractLowCodeHandlerFieldService {
    @PostConstruct
    public void register() {
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.DEPT.getType(), this);
    }

    @Override
    public Object handlerField(FieldAttrEntity fieldAttrEntity, JSONObject data, LowCodeExecuteServicePojo lowCodeExecuteServicePojo) throws XbbException {
        Long departmentId = data.getLong(fieldAttrEntity.getAttr());
        if (Objects.isNull(departmentId)) {
            return null;
        }
        Map<String, DepartmentEntity> departmentMap = lowCodeExecuteServicePojo.getUserAndDepartmentGetVO().getDepartmentMap();
        DepartmentEntity departmentEntity = departmentMap.get(String.valueOf(departmentId));
        DepartmentUserPojo departmentUserPojo = new DepartmentUserPojo();
        departmentUserPojo.setId(departmentId);
        if (Objects.nonNull(departmentEntity)) {
            departmentUserPojo.setName(departmentEntity.getName());
        }
        return departmentUserPojo;
    }
}
